# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html


# useful for handling different item types with a single interface
from itemadapter import ItemAdapter


class QkMovie099Pipeline:

    def open_spider(self, spider):
        self.fp = open('movie.json', 'w', encoding='utf-8')

    def process_item(self, item, spider):

        self.fp.write(str(item) + '\n')
        return item

    def close_spider(self, spider):
        self.fp.close()


import urllib.request
import os


class ImagesDownload:
    def __init__(self):
        if not os.path.exists('./images/'):
            os.makedirs('./images/')

    def process_item(self, item, spider):
        url = item.get('src')
        filename = './images/' + item.get('name', 'default') + '.jpg'

        try:
            urllib.request.urlretrieve(url=url, filename=filename)
        except Exception as e:
            spider.logger.error(f"下载图片失败 {url}: {e}")

        return item
